package com.dlry.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dlry.entity.DlLoginuser;
import com.dlry.entity.DlMeetingRoom;
import com.dlry.serviceImpl.MeetingRoomService;
import com.dlry.serviceImpl.UserService;

@Controller
@RequestMapping("/{roler}")
public class RoomController extends BaseController {
	@Autowired
	private MeetingRoomService roomService;
	@Autowired
	private UserService userService;

	@RequestMapping("/newroom")
	public String newRoom(@PathVariable("roler") String roler, Model model) {
		model.addAttribute("room", new DlMeetingRoom());
		model.addAttribute("roler", roler);
		return "newroom_jsp";
	}

	@RequestMapping(value = "/saveroom")
	public String addRoom(@Valid DlMeetingRoom room, BindingResult result, HttpServletResponse response,
			@PathVariable("roler") String roler, Model model) throws ParseException, IOException {

		if (result.hasErrors()) {
			model.addAttribute("room", room);
			model.addAttribute("roler", roler);
			model.addAttribute("errors", result);
			return "newroom_jsp";
		}
		DlLoginuser user = userService.findByName(getPrincipal());
		room.setUser(user);
		roomService.save(room);
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.println("提交成功，请关闭本页。");
		return null;
	}

	@RequestMapping("/deleteroom")
	public String deleteRoom(@PathVariable("roler") String roler, Long rId) {
		roomService.delete(rId);
		return "redirect:/" + roler + "/room";
	}
}
